package com.my.service
{

	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.InvokeEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;

	public class RemoteServiceFactory
	{
		private static var _instance:RemoteServiceFactory=new RemoteServiceFactory();


		public var userInfoService:RemoteObject;
		
		public function RemoteServiceFactory()
		{
			userInfoService=getConfiguredRO("userInfoService");
			
			
		}



		public static function getInstance():RemoteServiceFactory
		{
			return _instance;
		}

		//得到配置好的RemoteObject
		private function getConfiguredRO(destination:String):RemoteObject
		{
			var ro:RemoteObject=new RemoteObject(destination);
			ro.showBusyCursor=true;
			setEndPoint(ro);
			addAllEvent(ro);
			
			return ro;
		}

		private function setEndPoint(ro:RemoteObject):void
		{
			try
			{
//				Alert.show(ConfigService.getInstance().mainDataServiceURL+".............");
//				ro.endpoint="http://" + ConstVars.SERVER_IP_PORT + "/ManagementSys/messagebroker/amf";
				ro.endpoint = ConfigService.getInstance().mainDataServiceURL;
			}
			catch (e:Error)
			{
				trace(e.message);
			}
		}

		private function resultHandler(e:ResultEvent):void
		{
			FlexGlobals.topLevelApplication.mouseChildren=true;
			//FlexGlobals.topLevelApplication.loading.visible=false;
		}


		private function addResultEvent(ro:RemoteObject):void
		{
			ro.addEventListener(ResultEvent.RESULT, resultHandler);
		}


		/**
		 *
		 * @param e
		 *
		 */
		private function invokeHandler(e:InvokeEvent):void
		{
			FlexGlobals.topLevelApplication.mouseChildren=false;
			//FlexGlobals.topLevelApplication.loading.visible=true;
			//PopUpManager.bringToFront(FlexGlobals.topLevelApplication.loading);
		}


		private function addInvokeEvent(ro:RemoteObject):void
		{
			ro.addEventListener(InvokeEvent.INVOKE, invokeHandler);
		}


		private function faultHandler(e:FaultEvent):void
		{
			Alert.show(e.message.toString());
			FlexGlobals.topLevelApplication.mouseChildren=true;
			//	FlexGlobals.topLevelApplication.loading.visible=false;
			if (e.fault.faultCode == "Client.Error.DeliveryInDoubt")
			{
				return;
			}
			else
			{
				Alert.show("操作异常,请重新操作" + e.message);
			}
		}


		private function addFaultEvent(ro:RemoteObject):void
		{
			ro.addEventListener(FaultEvent.FAULT, faultHandler);
		}


		private function addAllEvent(ro:RemoteObject):void
		{
			addInvokeEvent(ro);
			addResultEvent(ro);
			addFaultEvent(ro);
		}
	}
}